package api

import (
	"encoding/json"
	"net/http"
	"new_sensitive/internal/model"

	"github.com/huichen/sego"
)

// SegmentHandler 分词处理器
type SegmentHandler struct {
	segmenter sego.Segmenter
}

// NewSegmentHandler 创建分词处理器
func NewSegmentHandler() *SegmentHandler {
	h := &SegmentHandler{}
	h.segmenter.LoadDictionary("dictionary.txt")
	return h
}

// ServeHTTP 处理分词请求
func (h *SegmentHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	// 只接受POST请求
	if r.Method != http.MethodPost {
		http.Error(w, "仅支持POST请求", http.StatusMethodNotAllowed)
		return
	}

	// 解析请求参数
	if err := r.ParseForm(); err != nil {
		http.Error(w, "解析请求参数失败", http.StatusBadRequest)
		return
	}

	// 获取文本内容
	text := r.FormValue("text")
	if text == "" {
		http.Error(w, "文本内容不能为空", http.StatusBadRequest)
		return
	}

	// 执行分词
	words := h.segment(text)

	// 构建响应
	resp := model.SegmentResponse{
		Text:  text,
		Words: words,
	}

	// 返回JSON响应
	w.Header().Set("Content-Type", "application/json")
	if err := json.NewEncoder(w).Encode(resp); err != nil {
		http.Error(w, "响应编码失败", http.StatusInternalServerError)
		return
	}
}

// segment 使用sego进行中文分词
func (h *SegmentHandler) segment(text string) []string {
	// 使用sego分词器进行分词
	segments := h.segmenter.Segment([]byte(text))

	// 提取分词结果
	words := make([]string, 0, len(segments))
	for _, seg := range segments {
		words = append(words, seg.Token().Text())
	}

	return words
}
